package com.example.app.pages.main.login

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.AccountCircle
import androidx.compose.material.icons.rounded.Lock
import androidx.compose.material3.ButtonColors
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ListItemDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import com.example.app.R
import com.example.app.barStateViewModel
import com.example.app.components.MyButton.MyFilledTonalButton
import com.example.app.components.MyIcon.MyIcon
import com.example.app.components.MyImage.MyImage
import com.example.app.components.MyListItem.MyListItem
import com.example.app.components.MyScaffold.MyScaffoldHasTipAndLoading
import com.example.app.components.MySpacer.MySpacer
import com.example.app.components.MyText.MyText
import com.example.app.components.MyTextField.MyTextField
import com.example.app.components.MyTextField.MyTextFieldState
import com.example.app.components.MyTip.MyTipState
import com.example.app.components.MyTip.MyTipType
import com.example.app.components.MyTopBar.MyTopBar
import com.example.app.loginViewModel
import com.example.app.mainViewModel
import com.example.app.pages.main.login.viewModel.LoginViewModel
import com.example.app.routeViewModel
import com.example.app.ui.theme.largeSpacer
import com.example.app.ui.theme.smallSpacer
import com.example.app.util.CacheUtil
import com.example.app.viewmodel.BarStateViewModel
import com.example.app.viewmodel.HomeChild
import com.example.app.viewmodel.MainPages
import com.example.app.viewmodel.MainViewModel
import com.example.app.viewmodel.RouteViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

var userNameTextFieldState = MyTextFieldState()
var passwordTextFieldState = MyTextFieldState()
var loginTipState = MyTipState()
@OptIn(
    ExperimentalMaterial3Api::class,
    ExperimentalComposeUiApi::class
)
@Composable
fun Login() {
    var scope = rememberCoroutineScope()
    var userName = userNameTextFieldState.textFieldValue.collectAsState()
    var password = passwordTextFieldState.textFieldValue.collectAsState()
    var userNameIsFocus = userNameTextFieldState.focus.collectAsState()
    var passwordIsFocus = passwordTextFieldState.focus.collectAsState()
    var userNameError = userNameTextFieldState.isError.collectAsState()
    var passwordError = passwordTextFieldState.isError.collectAsState()
    var userNameIsDirty = userNameTextFieldState.isDirty.collectAsState()
    var passwordIsDirty = passwordTextFieldState.isDirty.collectAsState()
    if (userName.value.text.isEmpty() && userNameIsDirty.value) {
        userNameTextFieldState.flowUpdate_errorMessage("请输入用户名")
        userNameTextFieldState.flowUpdate_isError(true)
    } else {
        userNameTextFieldState.flowUpdate_isError(false)
    }
    if (password.value.text.isEmpty() && passwordIsDirty.value) {
        passwordTextFieldState.flowUpdate_errorMessage("请输入密码")
        passwordTextFieldState.flowUpdate_isError(true)
    } else {
        passwordTextFieldState.flowUpdate_isError(false)
    }
    barStateViewModel.updateAll(
        isShowBottomBar = false,
        isStatusBarDarkIcon = true,
        statusBarColor = MaterialTheme.colorScheme.background,
        navigationBarColor = MaterialTheme.colorScheme.background,
        isNavigationBarDarkIcon = true
    )


    MyScaffoldHasTipAndLoading(
        topBar = {
            MyTopBar(
                title = {
                    MyText(
                        text = "登录",
                        style = MaterialTheme.typography.titleSmall
                    )
                })
        },
        content = {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(it),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                AnimatedVisibility(
                    visible = !userNameIsFocus.value && !passwordIsFocus.value
                ) {
                    Column(
                        modifier = Modifier.fillMaxWidth(),
                        verticalArrangement = Arrangement.Center,
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        MySpacer(modifier = Modifier.height(22.dp))
                        MyImage(
                            painter = painterResource(id = R.drawable.logo)
                        )
                        MySpacer(modifier = Modifier.height(smallSpacer))
                        MyText(
                            text = "Easy Book",
                            style = MaterialTheme.typography.titleSmall,
                            color = MaterialTheme.colorScheme.primary
                        )
                        MySpacer(modifier = Modifier.height(largeSpacer))
                    }
                }


                MyListItem(colors = ListItemDefaults.colors(containerColor = MaterialTheme.colorScheme.background),
                    headlineContent = {
                        MyTextField(
                            myTextFieldState = userNameTextFieldState,
                            leadingIcon = {
                                MyIcon(imageVector = Icons.Rounded.AccountCircle)
                            },
                            placeholder = {
                                MyText(text = "请输入用户名")
                            },
                            value = userName.value,
                            onValueChange = {
                                userNameTextFieldState.flowUpdate_textFieldValue(it)
                            },
                            label = {
                                MyText(text = "用户名")
                            },
                            isError = userNameError.value
                        )
                    })
                MySpacer(modifier = Modifier.height(smallSpacer))
                MyListItem(colors = ListItemDefaults.colors(containerColor = MaterialTheme.colorScheme.background),
                    headlineContent = {
                        MyTextField(
                            myTextFieldState = passwordTextFieldState,
                            leadingIcon = {
                                MyIcon(imageVector = Icons.Rounded.Lock)
                            },
                            placeholder = {
                                MyText(text = "请输入密码")
                            },
                            value = password.value,
                            onValueChange = {
                                passwordTextFieldState.flowUpdate_textFieldValue(it)
                            },
                            label = {
                                MyText(text = "密码")
                            },
                            isError = passwordError.value,
                            keyboardOptions = KeyboardOptions.Default.copy(
                                keyboardType = KeyboardType.Password
                            ),
                            visualTransformation = PasswordVisualTransformation()
                        )
                    })
                MySpacer(modifier = Modifier.height(smallSpacer))
                MyListItem(colors = ListItemDefaults.colors(containerColor = MaterialTheme.colorScheme.background),
                    headlineContent = {
                        MyFilledTonalButton(enabled = !userName.value.text.isEmpty() && !password.value.text.isEmpty(),
                            colors = ButtonColors(
                                containerColor = MaterialTheme.colorScheme.surfaceTint,
                                contentColor = MaterialTheme.colorScheme.onPrimary,
                                disabledContainerColor = ButtonDefaults.buttonColors().disabledContainerColor,
                                disabledContentColor = ButtonDefaults.buttonColors().disabledContentColor
                            ),
                            modifier = Modifier.fillMaxWidth(),
                            onClick = {
                                scope.launch {
                                    var result =
                                        loginViewModel.request_login(
                                            Username = userName.value.text,
                                            Password = password.value.text
                                        )
                                            .await()

                                    if (result.code < 1) {
                                        com.example.app.pages.main.mainTipState.show(description = "登录成功！")
                                        CacheUtil.setUser(result.data)
                                        //登录完成，存userinfo
                                        mainViewModel.flowUpdate_userInfo(CacheUtil.getUser()!!)
                                        routeViewModel.flowUpdate_curPage(
                                            MainPages.HOME
                                        )
                                        routeViewModel.flowUpdate_curHomeChild(
                                            HomeChild.ACCOUNT_LIST
                                        )
                                    } else {
                                        com.example.app.pages.main.mainTipState.show(
                                            description = "账号或者密码错误",
                                            type = MyTipType.FAIL
                                        )
                                    }
                                }
                            }) {
                            MyText(
                                text = "提交",
                                fontWeight = FontWeight.W500
                            )
                        }
                    })
            }
        })
}